package com.yanx.system.base.domain.manager;

import com.yanx.common.core.domain.manager.BaseManager;
import com.yanx.system.base.domain.entity.SysRole;
import com.yanx.system.base.domain.entity.rel.SysUserRole;
import com.yanx.system.base.domain.repository.SysRoleRepository;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Iterator;

/**
 * 菜单权限领域服务
 *
 * @author: gotanks
 * @create: 2023-2-10
 */
@Service
public class SysRoleManager extends BaseManager<SysRole, SysRoleRepository> {

    public boolean checkRoleNameUnique(String roleName, Long id) {
        int num = repository.countByRoleNameAndIdNot(roleName, id);
        return num > 0;
    }

    public boolean checkRoleKeyUnique(String roleKey, Long id) {
        int num = repository.countByRoleKeyAndIdNot(roleKey, id);
        return num > 0;
    }

    public void removeUserRoles(Long roleId, Long[] userIds) {
        repository.findById(roleId).ifPresent(role -> {
            Iterator<SysUserRole> iter = role.getUserRoles().iterator();
            while (iter.hasNext()) {
                SysUserRole next = iter.next();
                if (Arrays.asList(userIds).contains(next.getUserId())) {
                    iter.remove();
                }
            }
            repository.save(role);
        });
    }

    public void addUserRoles(Long roleId, Long[] userIds) {
        repository.findById(roleId).ifPresent(role -> {
            for (Long userId : userIds) {
                role.addUserRole(userId, roleId);
            }
            repository.save(role);
        });
    }
}
